﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace ZL_Framework
{
    [RequireComponent(typeof(AudioSource))]
    public class AudioItem : MonoBehaviour
    {
        public AudioSource m_AudioSource;
        public string AudioName;
        public bool IsPlaying
        {
            get
            {
                return m_AudioSource.isPlaying;
            }
        }

        private void Awake()
        {
            m_AudioSource = GetComponent<AudioSource>();
        }

        /// <summary>
        /// 播放
        /// </summary>
        /// <param name="_clip">音频</param>
        /// <param name="isLoop">是否循环</param>
        /// <param name="_volum">音量</param>
        /// <param name="action">播完事件</param>
        public void Play(AudioClip _clip, bool isLoop, float _volum = 1, Action action = null)
        {
            m_AudioSource.clip = _clip;
            m_AudioSource.loop = isLoop;
            m_AudioSource.volume = _volum;
            m_AudioSource.Play();
            AudioName = _clip.name;

            if (!isLoop)
            {
                SetPlayedCallback(action);
            }
        }

        /// <summary>
        /// 暂停
        /// </summary>
        public void Pause()
        {
            m_AudioSource.Pause();
            if (audioTimer != null)
            {
                audioTimer.IsPause = true;
            }
        }

        /// <summary>
        /// 继续
        /// </summary>
        public void Continue()
        {
            m_AudioSource.Play();
            if (audioTimer != null)
            {
                audioTimer.IsPause = false;
            }
        }

        /// <summary>
        /// 停止播放
        /// </summary>
        public void Stop()
        {
            m_AudioSource.Stop();
            Dispose();
        }    

        private Timer audioTimer;
        private void SetPlayedCallback(Action action)
        {
            float audioLength = m_AudioSource.clip.length;
            audioTimer = Timer.AddTimer(audioLength, AudioName).OnCompleted(() =>
            {
                PlayComplete(action);
            });
        }

        private void PlayComplete(Action action)
        {
            action?.Invoke();
            Dispose();
        }

        public void Dispose()
        {
            AudioManager.Instance.AllAudioItem.Remove(this);
            audioTimer?.Stop();
            audioTimer = null;
            GameObjectPool.Instance.CollectObject(gameObject);
            //Destroy(gameObject);
        }
    }
}